package com.xinchuang.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xinchuang.comment.R;
import com.xinchuang.common.KeyWordSystem;
import com.xinchuang.entity.User;
import com.xinchuang.entity.image.ImageResult;
import com.xinchuang.mapper.UserMapper;
import com.xinchuang.service.ImageService;
import com.xinchuang.service.UserService;
import com.xinchuang.service.image.ImageResultService;
import com.xinchuang.utils.DateUtils;
import com.xinchuang.utils.ObjectUtil;
import com.xinchuang.utils.ZipFileWriter;
import com.xinchuang.vo.PageVO;
import com.xinchuang.vo.ResultImageVO;
import io.swagger.models.auth.In;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ImageServiceImpl implements ImageService {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Resource
    private ImageResultService imageResultService;

    @Resource
    private KeyWordSystem keyWordSystem;

    @Resource
    private UserMapper userMapper;

    @Override
    public String reslutList(JSONObject jsonObject) {
        // 获取页码
        String pageNum = jsonObject.getString("pageNum");
        // 获取页容
        String pageSize = jsonObject.getString("pageSize");
        // 获取名称
        String imgName = jsonObject.getString("imgName");
        // 获取类型
        Integer type = jsonObject.getInteger("type");
        Page<ImageResult> imageResultPage = new Page<>(Integer.valueOf(pageNum), Integer.valueOf(pageSize));
        LambdaQueryWrapper<ImageResult> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(imgName)) {
            queryWrapper.like(ImageResult::getImageName, imgName);
        }
        queryWrapper.eq(ImageResult::getImageType, type);
        queryWrapper.orderByDesc(ImageResult::getCreateTime);
        Page<ImageResult> resultPage = imageResultService.page(imageResultPage, queryWrapper);
        PageVO pageVO = new PageVO();
        pageVO.setPageNum(Long.parseLong(pageNum));
        pageVO.setPageSize(Long.parseLong(pageSize));
        pageVO.setTotal(resultPage.getTotal());
        pageVO.setPageAll(resultPage.getPages());
        List imageList = Lists.newArrayList();
        resultPage.getRecords().forEach(imageResult -> {
            ResultImageVO resultImageVO = new ResultImageVO();
            resultImageVO.setImgName(StringUtils.isBlank(imageResult.getImageName()) ? "未命名" : imageResult.getImageName());
            resultImageVO.setTarId(imageResult.getId());
            LocalDate localDate = imageResult.getUpdateTime().toLocalDate();
            Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            resultImageVO.setUpdateTime(DateUtils.getDay(date));
            //缩略图
            resultImageVO.setIcon(keyWordSystem.getSERVER_URL() + imageResult.getResultThumb());
            //基础图
            resultImageVO.setBaseUrl(keyWordSystem.getSERVER_URL() + imageResult.getImageThumb());
            //成果图
            resultImageVO.setResultUrl(keyWordSystem.getSERVER_URL() + imageResult.getResultRelease());
            User user = userMapper.selectById(imageResult.getCreatePersion());
            resultImageVO.setUserName(ObjectUtil.isEmpty(user) ? " 用户已删除" : user.getName());
            imageList.add(resultImageVO);
        });
        pageVO.setImgList(imageList);
        return JSON.toJSONString(R.data(pageVO));
    }

    @Override
    public String correctResult(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String tarId = jsonObject.getString("tarId");
        ImageResult imageResult = imageResultService.getById(tarId);
        if (ObjectUtil.isNotEmpty(imageResult)) {
            JSONObject json = new JSONObject();
            json.put("url", keyWordSystem.getSERVER_URL() + imageResult.getImageThumb());
            json.put("newUrl", keyWordSystem.getSERVER_URL() + imageResult.getResultRelease());
            return JSON.toJSONString(R.data(json));
        }
        return JSON.toJSONString(R.fail(500, "暂无数据"));
    }

    @Override
    public String recognitionResult(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String tarId = jsonObject.getString("tarId");
        ImageResult imageResult = imageResultService.getById(tarId);
        if (ObjectUtil.isNotEmpty(imageResult)) {
            JSONObject json = new JSONObject();
            json.put("url", keyWordSystem.getSERVER_URL() + imageResult.getResultRelease());
            json.put("plotList", new ArrayList<>());
            return JSON.toJSONString(R.data(json));
        }
        return JSON.toJSONString(R.fail(500, "暂无数据"));
    }

    @Override
    public String rasterResult(JSONObject jsonObject) {
        //jsonobject解析获取标识
        String tarId = jsonObject.getString("tarId");
        ImageResult imageResult = imageResultService.getById(tarId);
        if (ObjectUtil.isNotEmpty(imageResult)) {
            JSONObject json = new JSONObject();
            json.put("url", keyWordSystem.getSERVER_URL() + imageResult.getResultRelease());
            return JSON.toJSONString(R.data(json));
        }
        return JSON.toJSONString(R.fail(500, "暂无数据"));
    }

    @Override
    public String resultDelete(JSONObject jsonObject) {
        // 获取类型
        String type = jsonObject.getString("type");
        // 获取标识
        JSONArray ids = jsonObject.getJSONArray("ids");
        List<String> strings = ids.toJavaList(String.class);
        strings.forEach(id -> {
            LambdaQueryWrapper<ImageResult> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ImageResult::getId, id)
                    .eq(ImageResult::getImageType, type);
            imageResultService.remove(queryWrapper);
        });
        return JSON.toJSONString(R.success("操作成功"));
    }

    @Override
    public String resultExport(JSONObject jsonObject) {
        //jsonobject解析获取类型
        String type = jsonObject.getString("type");
        //jsonobject解析获取标识
        JSONArray ids = jsonObject.getJSONArray("ids");
        if (CollectionUtil.isNotEmpty(ids)) {
            List<ImageResult> list = imageResultService.list(new LambdaQueryWrapper<ImageResult>()
                    .in(ImageResult::getId, ids.toArray())
                    .eq(ImageResult::getImageType, type));
            if (CollectionUtil.isNotEmpty(list)) {
                List<String> files = new ArrayList<>();
                for (ImageResult imageResult : list) {
                    files.add(keyWordSystem.getFILE_URL() + imageResult.getResultUrl());
                }
                String url = DateUtil.format(new Date(), "yyyyMMddHHmmssS");
                if (ZipFileWriter.createZip(files, keyWordSystem.getFILE_URL() + "/file/" + url)) {
                    JSONObject json = new JSONObject();
                    json.put("url", keyWordSystem.getSERVER_URL() + "/file/" + url + "/files.zip");
                    return JSON.toJSONString(R.data(json));
                }
            }
        }
        return JSON.toJSONString(R.fail(500, "暂无数据"));
    }

}
